<template>
  <view class="outbound-execute">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">
        <text class="nav-title">物料出库执行</text>
      </block>
    </cu-custom>

    <!-- 出库单信息 -->
    <view class="order-info-card">
      <view class="card-header">
        <text class="card-title">出库单信息</text>
      </view>
      <view class="info-grid">
        <view class="info-item">
          <text class="label">出库单号</text>
          <text class="value">{{ outboundInfo.outboundNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">出库类型</text>
          <text class="value">{{ outboundInfo.businessTypeName }}</text>
        </view>
        <view class="info-item">
          <text class="label">计划出库日期</text>
          <text class="value">{{ formatDate(outboundInfo.outboundDate) }}</text>
        </view>
        <view class="info-item">
          <text class="label">状态</text>
          <text class="status-badge" :class="outboundInfo.statusClass">
            {{ outboundInfo.statusText }}
          </text>
        </view>
      </view>
    </view>

    <!-- 出库明细列表 -->
    <view class="materials-section">
      <view class="section-header">
        <text class="section-title">出库明细</text>
        <view class="section-actions">
          <text class="section-count">共{{ materialList.length }}项</text>
          <view class="select-all-container" @click="toggleSelectAll">
            <view
              class="checkbox"
              :class="{
                checked: isAllSelected,
                indeterminate: isIndeterminate,
              }"
            >
              <text class="checkbox-icon">{{
                isAllSelected ? "✓" : isIndeterminate ? "−" : ""
              }}</text>
            </view>
            <text class="select-all-text">全选</text>
          </view>
        </view>
      </view>

      <view class="material-list">
        <view
          v-for="material in materialList"
          :key="material.id"
          class="material-item"
        >
          <view class="material-header">
            <view class="material-info">
              <view class="material-main">
                <text class="material-code">{{ material.materialCode }}</text>
                <text class="material-name">{{ material.materialName }}</text>
              </view>
              <text
                class="material-spec"
                v-if="material.specification || material.color"
                >{{ material.specification || "" }} |
                {{ material.color || "" }}</text
              >
            </view>
            <view class="material-quantity">
              <text class="quantity-label">需出库</text>
              <text class="quantity-value"
                >{{ material.quantity }}{{ material.unit }}</text
              >
              <!-- 选择状态指示器 -->
              <view class="selection-status">
                <text class="selection-text"
                  >{{ getMaterialSelectionStatus(material).selectedCount }}/{{
                    getMaterialSelectionStatus(material).totalCount
                  }}</text
                >
              </view>
            </view>
          </view>

          <!-- 分配方案 -->
          <view
            class="allocation-info"
            v-if="
              material.allocationPlans && material.allocationPlans.length > 0
            "
          >
            <view class="allocation-header">
              <text class="allocation-title">分配方案</text>
              <text class="allocation-summary"
                >共{{ material.allocationPlans.length }}个库位</text
              >
            </view>
            <view
              v-for="plan in material.allocationPlans"
              :key="plan.id"
              class="allocation-item"
              :class="plan.allocationItemClass"
              @click="togglePlanSelection(plan)"
            >
              <view class="allocation-checkbox">
                <view class="checkbox" :class="{ checked: plan.isSelected }">
                  <text class="checkbox-icon" v-if="plan.isSelected">✓</text>
                </view>
              </view>
              <view class="allocation-content">
                <view class="allocation-location">
                  <text class="warehouse-name">{{ plan.warehouseName }}</text>
                  <text class="location-name">{{ plan.locationName }}</text>
                </view>
                <view class="allocation-quantity">
                  <text class="allocated-amount"
                    >分配: {{ plan.allocationQuantity }}{{ plan.unit }}</text
                  >
                  <view class="quantity-display">
                    <text class="quantity-label">出库数量</text>
                    <text class="quantity-value"
                      >{{ plan.actualQuantity }}{{ plan.unit }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 库存不足提示 -->
          <view
            class="shortage-warning"
            v-if="material.remainingQuantity && material.remainingQuantity > 0"
          >
            <view class="warning-icon">⚠️</view>
            <view class="warning-content">
              <text class="warning-title">库存不足</text>
              <text class="warning-desc"
                >缺少 {{ material.remainingQuantity }}{{ material.unit
                }}，请及时补充库存</text
              >
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="cu-btn bg-grey lg" @click="goBack">取消</button>
      <button
        class="cu-btn bg-blue lg"
        @click="confirmOutbound"
        :disabled="!canSubmit"
      >
        确认出库 ({{ selectedPlanIds.length }})
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      outboundOrderId: "",
      outboundNo: "",
      outboundInfo: {},
      materialList: [],
      loading: false,
      selectedPlanIds: [], // 选中的分配方案ID列表
      selectAll: false, // 全选状态
    };
  },

  computed: {
    canSubmit() {
      // 检查是否选择了分配方案
      return this.selectedPlanIds.length > 0;
    },

    // 获取所有分配方案的总数
    totalPlansCount() {
      return this.materialList.reduce((total, material) => {
        return (
          total +
          (material.allocationPlans ? material.allocationPlans.length : 0)
        );
      }, 0);
    },

    // 检查是否全选
    isAllSelected() {
      return (
        this.totalPlansCount > 0 &&
        this.selectedPlanIds.length === this.totalPlansCount
      );
    },

    // 检查是否部分选择
    isIndeterminate() {
      return (
        this.selectedPlanIds.length > 0 &&
        this.selectedPlanIds.length < this.totalPlansCount
      );
    },
  },

  onLoad(options) {
    this.outboundOrderId = options.outboundOrderId;
    this.outboundNo = options.outboundNo;
    this.loadOutboundDetails();
  },

  methods: {
    // 加载出库单详情
    async loadOutboundDetails() {
      try {
        this.loading = true;
        uni.showLoading({ title: "加载中..." });

        const response = await this.$http.get(
          `/wms/outbound/detail/${this.outboundOrderId}`
        );

        if (response.data && response.data.success) {
          const result = response.data.result;

          // 设置出库单基本信息
          this.outboundInfo = {
            ...result.outbound,
            businessTypeName: this.mapOutboundType(
              result.outbound.outboundType
            ),
            statusClass: this.calculateStatusClass(result.outbound.status),
            statusText: this.mapStatus(result.outbound.status),
          };

          // 处理物料明细和分配计划
          const details = result.details || [];
          const allocationPlans = result.allocationPlans || [];

          this.materialList = details.map((detail) => {
            const detailPlans = allocationPlans.filter(
              (plan) =>
                plan.materialCode === detail.materialCode &&
                plan.specification === detail.specification &&
                plan.color === detail.color
            );

            // 只保留未出库的分配方案 (status = 0)
            const availablePlans = detailPlans.filter(plan => plan.status === 0);

            // 计算总分配数量
            const totalAllocated = detailPlans.reduce((sum, plan) => sum + (plan.allocationQuantity || 0), 0);
            // 计算缺少数量
            const remainingQuantity = Math.max(0, detail.quantity - totalAllocated);

            return {
              ...detail,
              remainingQuantity, // 缺少的数量
              allocationPlans: availablePlans.map((plan) => ({
                ...plan,
                actualQuantity: plan.allocationQuantity, // 默认实际数量等于分配数量，不可修改
                isSelected: false, // 是否选中
                allocationItemClass: this.calculateAllocationItemClass(plan),
                inputFieldClass: this.calculateInputFieldClass(plan),
              })),
            };
          }).filter(detail => detail.allocationPlans.length > 0); // 过滤掉没有可用分配方案的明细
        }
      } catch (error) {
        console.error("加载出库详情失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },

    // 切换分配方案选择状态
    togglePlanSelection(plan) {
      plan.isSelected = !plan.isSelected;

      if (plan.isSelected) {
        if (!this.selectedPlanIds.includes(plan.id)) {
          this.selectedPlanIds.push(plan.id);
        }
      } else {
        const index = this.selectedPlanIds.indexOf(plan.id);
        if (index > -1) {
          this.selectedPlanIds.splice(index, 1);
        }
      }

      // 更新样式类
      plan.allocationItemClass = this.calculateAllocationItemClass(plan);
    },

    // 全选/取消全选
    toggleSelectAll() {
      const shouldSelectAll = !this.isAllSelected;
      this.selectedPlanIds = [];

      this.materialList.forEach((material) => {
        if (material.allocationPlans) {
          material.allocationPlans.forEach((plan) => {
            plan.isSelected = shouldSelectAll;
            if (shouldSelectAll) {
              this.selectedPlanIds.push(plan.id);
            }
            plan.allocationItemClass = this.calculateAllocationItemClass(plan);
          });
        }
      });
    },

    // 获取物料的选择状态
    getMaterialSelectionStatus(material) {
      if (!material.allocationPlans || material.allocationPlans.length === 0) {
        return {
          selectedCount: 0,
          totalCount: 0,
          isAllSelected: false,
          isPartialSelected: false,
        };
      }

      const selectedCount = material.allocationPlans.filter(
        (plan) => plan.isSelected
      ).length;
      const totalCount = material.allocationPlans.length;

      return {
        selectedCount,
        totalCount,
        isAllSelected: selectedCount === totalCount && totalCount > 0,
        isPartialSelected: selectedCount > 0 && selectedCount < totalCount,
      };
    },

    // 计算分配项的状态样式
    calculateAllocationItemClass(plan) {
      if (plan.isSelected) {
        return "allocation-item-selected";
      }
      return "allocation-item-normal";
    },

    // 计算输入框状态样式
    calculateInputFieldClass(plan) {
      return "quantity-field-readonly";
    },

    // 确认出库
    async confirmOutbound() {
      if (this.selectedPlanIds.length === 0) {
        uni.showToast({
          title: "请选择要出库的分配方案",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认出库",
        content: `已选择${this.selectedPlanIds.length}个分配方案，确认执行出库操作？`,
        showCancel: true,
        confirmText: "确认出库",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            this.executeOutbound();
          }
        },
      });
    },

    // 执行出库操作
    async executeOutbound() {
      try {
        uni.showLoading({ title: "执行出库中..." });

        const response = await this.$http.put(
          "/wms/outbound/oneClickOutboundForMobile",
          {
            id: this.outboundOrderId,
            planIdList: this.selectedPlanIds,
          }
        );

        if (response.data && response.data.success) {
          uni.showToast({
            title: "出库成功",
            icon: "success",
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.data.message || "出库失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("执行出库失败:", error);
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "暂无";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")}`;
    },

    // 状态映射
    mapStatus(status) {
      const statusMap = {
        1: "待审核",
        2: "已审核",
        3: "已出库",
        4: "已驳回",
        5: "部分出库",
      };
      return statusMap[status] || "未知状态";
    },

    // 出库类型映射
    mapOutboundType(outboundType) {
      const typeMap = {
        4: "其他出库",
        21: "生产领料出库",
        22: "仓库调拨出库",
        29: "其他出库",
        31: "补充出库",
      };
      return typeMap[outboundType] || "未知类型";
    },

    // 计算状态样式类
    calculateStatusClass(status) {
      const classMap = {
        1: "status-pending",
        2: "status-completed",
        3: "status-partial",
        4: "status-rejected",
        5: "status-pending",
      };
      return classMap[status] || "status-unknown";
    },
  },
};
</script>

<style lang="scss" scoped>
.outbound-execute {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: white;
}

// 出库单信息卡片
.order-info-card {
  background: white;
  margin: 24rpx;
  border-radius: 16rpx;
  padding: 24rpx;
}

.card-header {
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.label {
  font-size: 24rpx;
  color: #999;
}

.value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.status-badge {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
  font-weight: 500;
  align-self: flex-start;

  &.status-pending {
    background: #fff3cd;
    color: #856404;
  }

  &.status-completed {
    background: #d4edda;
    color: #155724;
  }

  &.status-partial {
    background: #cce5ff;
    color: #004085;
  }

  &.status-rejected {
    background: #f8d7da;
    color: #721c24;
  }
}

// 物料明细区域
.materials-section {
  margin: 24rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.section-count {
  font-size: 24rpx;
  color: #666;
  background: #f8f9fa;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.select-all-container {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 12rpx;
  border-radius: 16rpx;
  background: #f0f8ff;
  border: 1rpx solid #007aff;
}

.select-all-text {
  font-size: 24rpx;
  color: #007aff;
  font-weight: 500;
}

.material-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.material-item {
  background: white;
  border-radius: 20rpx;
  padding: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.material-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.material-info {
  flex: 1;
}

.material-main {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  margin-bottom: 12rpx;
}

.material-code {
  font-size: 32rpx;
  font-weight: 700;
  color: #1a1a1a;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.material-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.material-spec {
  font-size: 24rpx;
  color: #666;
  background: #f8f9fa;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  align-self: flex-start;
}

.material-quantity {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  position: relative;
}

.quantity-label {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 6rpx;
}

.quantity-value {
  font-size: 30rpx;
  font-weight: 700;
  color: #e74c3c;
  background: #fff5f5;
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  border: 2rpx solid #fee;
}

// 选择状态指示器
.selection-status {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  background: #007aff;
  border-radius: 12rpx;
  padding: 4rpx 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
}

.selection-text {
  font-size: 20rpx;
  color: white;
  font-weight: 600;
}

// 复选框样式
.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #dee2e6;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  transition: all 0.3s ease;

  &.checked {
    background: #007aff;
    border-color: #007aff;
  }

  &.indeterminate {
    background: #6c757d;
    border-color: #6c757d;
  }
}

.checkbox-icon {
  font-size: 24rpx;
  color: white;
  font-weight: 700;
}

// 分配信息样式
.allocation-info {
  margin-top: 20rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 20rpx;
}

.allocation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.allocation-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #495057;
}

.allocation-summary {
  font-size: 22rpx;
  color: #6c757d;
  background: #e9ecef;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.allocation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 12rpx;
  border: 2rpx solid #e9ecef;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

  &:last-child {
    margin-bottom: 0;
  }

  // 分配状态样式
  &.allocation-item-normal {
    border-color: #e9ecef;
    background: white;
  }

  &.allocation-item-selected {
    border-color: #007aff;
    background: #f0f8ff;
    box-shadow: 0 2rpx 12rpx rgba(0, 122, 255, 0.15);
  }
}

// 分配项复选框
.allocation-checkbox {
  margin-right: 16rpx;
  display: flex;
  align-items: center;
}

.allocation-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.allocation-location {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.warehouse-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 2rpx;
}

.location-name {
  font-size: 26rpx;
  color: #495057;
  font-weight: 500;
}

.location-code {
  font-size: 22rpx;
  color: #6c757d;
  background: #e9ecef;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  align-self: flex-start;
  margin-top: 4rpx;
}

.allocation-quantity {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12rpx;
}

.allocated-amount {
  font-size: 24rpx;
  color: #007aff;
  font-weight: 600;
  background: #f0f8ff;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.quantity-display {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4rpx;
}

.quantity-label {
  font-size: 20rpx;
  color: #6c757d;
  font-weight: 500;
}

.quantity-value {
  font-size: 24rpx;
  color: #007aff;
  font-weight: 600;
  background: #f0f8ff;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

// 输入错误动画
@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-4rpx);
  }
  75% {
    transform: translateX(4rpx);
  }
}

// 库存不足提示
.shortage-warning {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border: 2rpx solid #ff9500;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 149, 0, 0.15);
}

.warning-icon {
  font-size: 32rpx;
  line-height: 1;
}

.warning-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.warning-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #ff6b00;
  line-height: 1.2;
}

.warning-desc {
  font-size: 24rpx;
  color: #bf5000;
  line-height: 1.4;
}

// 底部操作按钮
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20rpx;
  z-index: 100;

  .cu-btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 12rpx;
    font-size: 32rpx;
  }
}
</style>
